<template>
    <div>
        <div class="top">
            <div class="biaoti">考试系统</div>
            <div>
                <button @click="goToLogin">登录</button>
                <button @click="goToRegister">注册</button>
            </div>
        </div>
        <div class="login-wrap">
            <div class="image-container">
                <img src="../assets/img/login.jpg" alt="Login Image" class="login-image" />
            </div>
            <el-form :label-position="labelPosition" label-width="auto" :model="formLabelAlign" class="login-container"
                :rules="rules" ref="ruleFormRef">
                <div class="login-type">
                    <div :class="{ 'active': selectedLoginType === 'student' }" @click="selectLoginType('student')">学生登录
                    </div>
                    <div :class="{ 'active': selectedLoginType === 'teacher' }" @click="selectLoginType('teacher')">老师登录
                    </div>
                </div>
                <el-form-item prop="studentId">
                    <el-input v-model="formLabelAlign.studentId"
                        :placeholder="selectedLoginType === 'teacher' ? '请输入身份证号码' : '请输入学生学号'" clearable />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="formLabelAlign.password" type="password" placeholder="请输入密码" show-password
                        clearable />
                </el-form-item>
                <el-form-item prop="code">
                    <div class="code-container">
                        <el-input v-model="formLabelAlign.code" placeholder="请输入验证码" clearable style="width: 65%;" />
                        <Captcha v-model:code="randomCode" class="code-img" />
                    </div>
                </el-form-item>
                <el-form-item class="btn-box">
                    <el-checkbox v-model="remember" class="remember" label="记住密码" size="large"
                        @change="handleRememberChange" />
                    <router-link class="link-div" :to="{ path: '/register' }">学生注册</router-link>
                </el-form-item>
                <!-- 按钮提交组 -->
                <el-form-item class="btn-box">
                    <el-button type="primary" native-type="reset" style="width: 40%;">重置</el-button>
                    <el-button type="success" style="width: 40%;" native-type="submit"
                        @click.prevent="submitForm">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 底部信息 -->
        <div class="footer">
            帮助中心 | 服务支持 | 售后服务 | 服务网点 | 线下门店 | 申请商家 | 加入我们 | 关于我们 | 友情链接
            <p>©福福传媒出品</p>
        </div>
    </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { reactive, ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router';
import { useUser } from '../stores/userInfo';
import Captcha from '../components/Captcha.vue';
import axios from 'axios';

const userStore = useUser()
const router = useRouter()
const labelPosition = ref('right')
const remember = ref(false)
const ruleFormRef = ref()
const formLabelAlign = reactive({
    studentId: '',
    password: '',
    code: '',
})
// 记录当前选中的登录类型
const selectedLoginType = ref('student')
// 随机验证码
const randomCode = ref('');

// 生成随机验证码
const generateRandomCode = () => {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let code = '';
    for (let i = 0; i < 4; i++) {
        code += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return code;
};

// 使用 computed 动态计算 rules
const rules = computed(() => {
    return {
        studentId: [
            {
                required: true,
                message: () => selectedLoginType.value === 'teacher' ? '请输入身份证号码' : '请输入学生学号',
                trigger: 'blur'
            }
        ],
        password: [
            {
                required: true,
                message: '请输入密码',
                trigger: 'blur'
            }
        ],
        code: [
            {
                required: true,
                message: '请输入验证码',
                trigger: 'blur'
            }
        ],
    };
});

// 选择登录类型
const selectLoginType = (type) => {
    selectedLoginType.value = type
    // 清空表单验证
    ruleFormRef.value?.clearValidate()
}

/// 登录按钮事件
const submitForm = () => {
    ruleFormRef.value?.validate((valid, fields) => {
        if (valid) {
            // 验证码不区分大小写比较
            const isCodeValid = formLabelAlign.code.toLowerCase() === randomCode.value.toLowerCase();
            
            // 根据登录类型进行不同处理
            if (selectedLoginType.value === 'teacher') {
                // 老师登录逻辑
                if (formLabelAlign.studentId === '1' && formLabelAlign.password === '1' && isCodeValid) {
                    ElMessage.success('老师登录成功')
                    sessionStorage.setItem('userInfo', JSON.stringify({
                        studentId: formLabelAlign.studentId,
                        password: formLabelAlign.password,
                        type: 'teacher'
                    }))
                    router.push('/main')
                } else {
                    ElMessage.error('账号密码或验证码错误')
                }
            } else {
                // 学生登录逻辑
                if (userStore.userInfo.studentId) {
                    const { studentId, password } = userStore.userInfo
                    if (formLabelAlign.studentId === studentId && formLabelAlign.password === password && isCodeValid) {
                        ElMessage.success('学生登录成功')
                        if (remember.value) {
                            sessionStorage.setItem('formLabelAlign', JSON.stringify({
                                ...formLabelAlign, status: remember.value
                            }))
                        }
                        router.push('/student/home')
                    } else {
                        ElMessage.error('账号密码或验证码错误')
                    }
                } else {
                    router.push('/register')
                }
            }
        } else {
            ElMessage.error('验证失败')
        }
    })
}
// 记住密码的状态
const handleRememberChange = (status) => {
    if (status) {
        // 如果为true保存数据
        sessionStorage.setItem('formLabelAlign', JSON.stringify({
            ...formLabelAlign,
            status: remember.value
        }))
    } else {
        // 如果为false就清空数据
        sessionStorage.removeItem('formLabelAlign')
    }
}
// 跳转到登录页面
const goToLogin = () => {
    router.push('/login');
}
// 跳转到注册页面
const goToRegister = () => {
    router.push('/register');
}

onMounted(async () => {
    randomCode.value = generateRandomCode();
    if (sessionStorage.getItem('formLabelAlign')) {
        const { studentId, password, code, status } = JSON.parse(sessionStorage.getItem('formLabelAlign'))
        formLabelAlign.studentId = studentId
        formLabelAlign.password = password
        formLabelAlign.code = code
        remember.value = status
    }

    // 测试后端连接
    try {
        await axios.get('http://192.168.59.164:8081/api/hello');
        console.log('后端连接成功');
    } catch (error) {
        console.error('后端连接失败:', error);
        ElMessage.error('后端服务连接失败，请检查服务是否正常运行');
    }
})
</script>

<style scoped>
/* 样式保持不变 */
.top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
}

.biaoti {
    margin-left: 20px;
    font-size: 20px;
}

.top button {
    border: 2px solid #03BB7A;
    padding: 8px 16px;
    cursor: pointer;
    margin-left: 10px;
    border-radius: 8px;
    /* 添加圆角边框 */
}

.top button:nth-of-type(1) {
    background-color: white;
    color: #03BB7A;
}

.top button:nth-of-type(2) {
    background-color: #03BB7A;
    color: white;
}

.login-wrap {
    box-sizing: border-box;
    width: 100vw;
    height: 80vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #EEEEEE;
}

.image-container {
    margin-right: 100px;
    /* 图片与表单之间的间距 */
}

.login-image {
    width: 500px;
    /* 根据需要调整图片大小 */
    height: auto;
}

.login-container {
    width: 300px;
    padding: 35px;
    background-color: #ffffff;
    border-radius: 6px;
    box-shadow: 0 0 20px 0 #ffff;
}

.el-input {
    height: 38px;
}

.code-container {
    display: flex;
    align-items: center;
    gap: 8px;
}

.code-img {
    flex-shrink: 0;
}

.link-div {
    color: red;
    text-decoration: none;
    font-family: sans-serif;
    font-size: 10px;
}

::v-deep(.btn-box>.el-form-item__content) {
    display: flex;
    justify-content: space-between;
}

.login-type {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
}

.login-type div {
    cursor: pointer;
}

.active {
    color: #03BB7A;
    text-decoration: underline;
    text-decoration-color: #03BB7A;
    font-weight: bold;
    text-decoration-skip-ink: none;
    text-underline-offset: 5px;
    /* 调整下划线和字体之间的间距 */
}

/* 底部样式 */
.footer {
    background-color: black;
    color: white;
    text-align: center;
    padding: 10px;
}
</style>